package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端token校验拦截器
 *
 * @Author mr.Candy
 * @Date 2025/5/259:58
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 拦截逻辑
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        //针对非控制器资源（或静态资源）直接放行
//        if(!(handler instanceof HandlerMethod)){
//            return true;
//        }

        //1.获取请求头中的token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //2.如果token为空，则响应401
        if (StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("token为空，请登陆");
        }
        //3.解析token
        try {
            Claims claims = tokenService.parseToken(token);
            //5.解析成功，就获取用户id放在threadlocal中
            Object userIdObj = claims.get("userId");
            Long userId = Long.valueOf(String.valueOf(userIdObj));
            UserThreadLocal.set(userId);

        } catch (Exception e) {
            e.printStackTrace();
            //4.如果解析失败，返回401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("token解析失败，请登陆");
        }
        //6.放行
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove(); //释放资源
    }
}
